﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using SLLottery.LotterySrv;
using SLLottery.Common;
using System.Net.NetworkInformation;
using System.Threading;
using System.ServiceModel;
using System.Runtime.InteropServices.Automation;
using System.Windows.Threading;
using System.Reflection;
namespace SLLottery
{
    public partial class LoginPage : UserControl
    {
        LotterySrv.LotteryServiceClient srv;
        UserAgreementWindow uaw;
        DispatcherTimer downloading_timer;
        public LoginPage()
        {
            InitializeComponent();
            srv = WcfProxy.GetProxy;
            uaw = new UserAgreementWindow();
            downloading_timer = new DispatcherTimer();
            downloading_timer.Interval = TimeSpan.FromSeconds(60);
            downloading_timer.Tick += new EventHandler(downloading_timer_Tick);
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
            Application.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted);
            srv.ValidateLoginCompleted += new EventHandler<ValidateLoginCompletedEventArgs>(srv_ValidateLoginCompleted);
            srv.GetLotteryTypeCompleted += new EventHandler<GetLotteryTypeCompletedEventArgs>(srv_GetLotteryTypeCompleted);
            srv.GetOverAllCfgCompleted += new EventHandler<GetOverAllCfgCompletedEventArgs>(srv_GetOverAllCfgCompleted);
            srv.GetPlayTypeInfoCompleted += new EventHandler<GetPlayTypeInfoCompletedEventArgs>(srv_GetPlayTypeInfoCompleted);
            srv.GetPlayTypeNumCompleted += new EventHandler<GetPlayTypeNumCompletedEventArgs>(srv_GetPlayTypeNumCompleted);
            srv.GetPlayTypeRadioCompleted += new EventHandler<GetPlayTypeRadioCompletedEventArgs>(srv_GetPlayTypeRadioCompleted);
            srv.GetVersionCompleted += new EventHandler<GetVersionCompletedEventArgs>(srv_GetVersionCompleted);
            uaw.Closed += new EventHandler(uaw_Closed);
            //界面初始化事件            
            this.Loaded += new RoutedEventHandler(LoginPage_Loaded);        //按钮点击事件            
            InstallButton.Click += InstClick;
            //Application.InstallStateChanged 事件            
            //在 InstallState 属性值更改时发生。            
            Application.Current.InstallStateChanged += OnInstallStateChanged;
            this.lbVer.Text = Assembly.GetExecutingAssembly().FullName.Split(',')[1].Trim().Replace("Version=", "Ver ");
            this.KeyDown += new KeyEventHandler(LoginPage_KeyDown);
        }

        void srv_GetVersionCompleted(object sender, GetVersionCompletedEventArgs e)
        {
            if (e.Result == null ||
                Assembly.GetExecutingAssembly().FullName.Split(',')[1].Trim().Replace("Version=", "") != e.Result)
                Application.Current.CheckAndDownloadUpdateAsync();
            else
            {
                UpdateUserInterface();
                gridLoading.Visibility = Visibility.Collapsed;
                btLogin.IsEnabled = true;
            }
        }

        void downloading_timer_Tick(object sender, EventArgs e)
        {
            loadingText.Text = "更新完毕，请重新运行程序!";
            progressBar.Visibility = Visibility.Collapsed;
            downloading_timer.Stop();
        }

        void srv_GetPlayTypeRadioCompleted(object sender, GetPlayTypeRadioCompletedEventArgs e)
        {
            App.Session[Constant.PLAYTYPERADIO_SESSION] = e.Result.ToList();
            gridLoading.Visibility = Visibility.Collapsed;
            btLogin.IsEnabled = true;
            uaw.Show();
        }

        void srv_GetPlayTypeNumCompleted(object sender, GetPlayTypeNumCompletedEventArgs e)
        {
            App.Session[Constant.PLAYTYPENUM_SESSION] = e.Result.ToList();
            srv.GetPlayTypeRadioAsync();
        }

        void srv_GetPlayTypeInfoCompleted(object sender, GetPlayTypeInfoCompletedEventArgs e)
        {
            App.Session[Constant.PLAYTYPE_SESSION] = e.Result.ToList();
            srv.GetPlayTypeNumAsync();
        }

        void srv_GetOverAllCfgCompleted(object sender, GetOverAllCfgCompletedEventArgs e)
        {
            srv.GetLotteryTypeAsync();
            if (e.Result.Keys.Contains("MaxBetCount"))
                Constant.MaxBetCount = double.Parse(e.Result["MaxBetCount"]);

            if (e.Result.Keys.Contains("MaxBetMoney"))
                Constant.MaxBetMoney = double.Parse(e.Result["MaxBetMoney"]);

            if (e.Result.Keys.Contains("MinOneBetMoney"))
                Constant.MinOneBetMoney = double.Parse(e.Result["MinOneBetMoney"]);

            if (e.Result.Keys.Contains("MaxOneBetMoney"))
                Constant.MaxOneBetMoney = double.Parse(e.Result["MaxOneBetMoney"]);

            if (e.Result.Keys.Contains("MaxOutMoneyOneDay"))
                Constant.MaxOutMoneyOneDay = double.Parse(e.Result["MaxOutMoneyOneDay"]);

            if (e.Result.Keys.Contains("MaxOutMoneyOneTime"))
                Constant.MaxOutMoneyOneTime = double.Parse(e.Result["MaxOutMoneyOneTime"]);

            if (e.Result.Keys.Contains("MinOutMoneyOneTime"))
                Constant.MinOutMoneyOneTime = double.Parse(e.Result["MinOutMoneyOneTime"]);

            if (e.Result.Keys.Contains("MaxOutMoneyTimesOneDay"))
                Constant.MaxOutMoneyTimesOneDay = Convert.ToInt32(e.Result["MaxOutMoneyTimesOneDay"]);

            if (e.Result.Keys.Contains("MaxBonusPct"))
                Constant.MaxBonusPct = double.Parse(e.Result["MaxBonusPct"]);
            if (e.Result.Keys.Contains("KFSystem"))
            {
                Constant.KFSystem = e.Result["KFSystem"].ToString();
            }
            if (e.Result.Keys.Contains("MemBonusIncrement"))
            {
                Constant.MemBonusIncrement = Convert.ToDouble(e.Result["MemBonusIncrement"].ToString());
            }
        }

        void srv_GetLotteryTypeCompleted(object sender, GetLotteryTypeCompletedEventArgs erg)
        {
            App.Session[Constant.LOTTERYPLAYTYPE_SESSION] = erg.Result.ToList();
            srv.GetPlayTypeInfoAsync();
        }

        void LoginPage_Loaded(object sender, RoutedEventArgs e)
        {
            //1、检查更新
            //2、检查线路
            //3、连接服务器
            //4、开始登录
            if (Application.Current.IsRunningOutOfBrowser)
            {
                loadingText.Text = "正在检查更新...";
                gridLoading.Visibility = Visibility.Visible;
                btLogin.IsEnabled = false;
                srv.GetVersionAsync();
            }
            else
            {
                if (Application.Current.InstallState == InstallState.Installed)
                {
                    IBInstalledExperience.Visibility = Visibility.Visible;
                    IBNotInstalledExperience.Visibility = Visibility.Collapsed;
                    OobExperience.Visibility = Visibility.Collapsed;
                }
                else
                {
                    IBNotInstalledExperience.Visibility = Visibility.Visible;
                    IBInstalledExperience.Visibility = Visibility.Collapsed;
                    OobExperience.Visibility = Visibility.Collapsed;
                }
            }
        }
        void LoginPage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.PlatformKeyCode == 13)
                this.btLogin_Click(this.btLogin, null);
        }
        /// <summary>        
        /// 更新用户界面        
        /// </summary>        
        private void UpdateUserInterface()
        {          
            if (Application.Current.IsRunningOutOfBrowser)
            {             
                OobExperience.Visibility = Visibility.Visible;
                this.tbUserName.Focus();
                IBNotInstalledExperience.Visibility = Visibility.Collapsed;
                IBInstalledExperience.Visibility = Visibility.Collapsed;
                this.rectMask.Visibility = Visibility.Visible;
                this.rectBack.Visibility = Visibility.Visible;
            }
            else
            {            
                if (Application.Current.InstallState == InstallState.Installed)
                {               
                    IBInstalledExperience.Visibility = Visibility.Visible;                 
                    IBNotInstalledExperience.Visibility = Visibility.Collapsed;
                    OobExperience.Visibility = Visibility.Collapsed;
                }
                else
                {                
                    IBNotInstalledExperience.Visibility = Visibility.Visible;                 
                    IBInstalledExperience.Visibility = Visibility.Collapsed;
                    OobExperience.Visibility = Visibility.Collapsed;
                }
            }
        }
        void OnInstallStateChanged(object sender, EventArgs e)
        {
            UpdateUserInterface();
        }
        void InstClick(object sender, RoutedEventArgs e)
        {     
            Application.Current.Install();
        }

        private void btLogin_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                gridLoading.Visibility = Visibility.Visible;
                btLogin.IsEnabled = false;
                loadingText.Text = "开始连接服务器";
                CheckWcfIsEnabled();
            }
            catch
            {
                gridLoading.Visibility = Visibility.Collapsed;
                btLogin.IsEnabled = true;
                Messager.Show("服务器暂时无法连接，请稍后再试!");
            }
        }
        void CheckWcfIsEnabled()
        {
            BasicHttpBinding myBinding = new BasicHttpBinding();
            EndpointAddress myEndpoint = new EndpointAddress(Constant.WcfSrvIp);
            ChannelFactory<ILotteryService> myChannelFactory = new ChannelFactory<ILotteryService>(myBinding, myEndpoint);

            ILotteryService wcfClient = myChannelFactory.CreateChannel();
            try
            {
                IDisposable chanel = wcfClient as IDisposable;

                ICommunicationObject o = chanel as ICommunicationObject;

                o.Opened += new EventHandler(Validatelogin);
                o.Open();
                o.Close();
            }
            catch
            {
                Messager.Show("服务器暂时无法连接，请稍后再试!");
            }
        }
        void Validatelogin(object sender, EventArgs e)
        {
            try
            {
                if (!Common.Common.ValidateUserID(this.tbUserName.Text.Trim()))
                {
                    Messager.Show("账号输入错误!");
                    gridLoading.Visibility = Visibility.Collapsed;
                    btLogin.IsEnabled = true;
                    return;
                }
                if (!Common.Common.ValidateInput(this.tbPassWord.Password))
                {
                    Messager.Show("密码输入错误!");
                    gridLoading.Visibility = Visibility.Collapsed;
                    btLogin.IsEnabled = true;
                    return;
                }
                loadingText.Text = "正在验证登录";
                srv.ValidateLoginAsync(this.tbUserName.Text.Trim(), this.tbPassWord.Password.Trim());//验证登录
            }
            catch
            {
                gridLoading.Visibility = Visibility.Collapsed;
                btLogin.IsEnabled = true;
                Messager.Show("登录失败，请稍后再试!");
            }
        }
        void srv_ValidateLoginCompleted(object sender, ValidateLoginCompletedEventArgs e)
        {
            if (e.Result)
            {
                srv.GetOverAllCfgAsync();
                loadingText.Text = "正在获取主界面配置参数";
            }
            else
            {
                gridLoading.Visibility = Visibility.Collapsed;
                btLogin.IsEnabled = true;
                Messager.Show("用户名或者密码错误!");
            }
            //gridLoading.Visibility = Visibility.Collapsed;
            //btLogin.IsEnabled = true;
            //if (e.Result)
            //{
            //    uaw.Show();
            //}
            //else
            //{
            //    Messager.Show("用户名或者密码错误!");
            //}
        }

        void uaw_Closed(object sender, EventArgs e)
        {
            bool? result = uaw.DialogResult;
            if (result.HasValue && result.Value)
            {
                App.Session[Constant.USERNAME_SESSION] = tbUserName.Text.Trim();
                App.Navigation(new MainPage());
            }
            else
                App.Navigation(new LoginPage());
        }
        //检查网络状态...
        private bool isConnected = (NetworkInterface.GetIsNetworkAvailable());

        public bool IsConnected
        {
            get
            {
                return isConnected;
            }
        }
        void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            this.isConnected = (NetworkInterface.GetIsNetworkAvailable());
            if (!isConnected)
            {
                MainPage.dicWs.Clear();
                App.Session.Clear();
                Messager.Show("网络异常、您的网络连接不可用!");
            }
        }
        void Current_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            
            if (e.UpdateAvailable)
            {
                //MessageBox.Show(App.Current.InstallState.ToString());
                //loadingText.Text = "正在更新,请稍等60秒左右!";
                //downloading_timer.Start();
                loadingText.Text = "更新完毕，请重新运行程序!";
                progressBar.Visibility = Visibility.Collapsed;
            }
            else
            {
                if (e.Error != null && e.Error is PlatformNotSupportedException)
                {
                    Messager.Show("程序更新错误!");
                    return;
                }
                UpdateUserInterface();
                gridLoading.Visibility = Visibility.Collapsed;
                btLogin.IsEnabled = true;
            }
        }
    }
}
